package com.mx.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;

@Slf4j
public class QiNiuUtil {
    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "RI_nUAhIlMElPW98QxQckQOBHPSZCwZCCZvqn4Tw";
    private static final String SECRET_KEY = "BrdYIUx7BC4tOiFz_eNwlmMDupDzdywpI2JYobjd";

    // 要上传的空间名称
    private static final String BUCKETNAME = "mx2432544821";

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 外链默认域名
    private static final String DOMAIN = "qhixpzwpb.hn-bkt.clouddn.com";


    /**
     * 将图片上传到七牛云
     */
    public static String uploadQNImg(FileInputStream file, String key) {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
        UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone2()));
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY );
        // 根据命名空间生成的上传token
        String path=null;
        String token = auth.uploadToken(BUCKETNAME);
        try{
            // 上传图片文件
            Response res = uploadManager.put(file, key, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);

            path = DOMAIN + "/" + putRet.key;
            // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片

        }catch (QiniuException e){
            e.printStackTrace();
        }
        return "http://"+path;
    }
}
